﻿using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Contracts.Interface.Iridgepletype;
using IntelligentAgriculture.Domain;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Domain.Interface;
using IntelligentAgriculture.Domain.Interface.IColumnManagement;
using IntelligentAgriculture.Domain.Interface.IEarTagReposiotry;
using IntelligentAgriculture.Domain.Interface.Iridgepletype;
using IntelligentAgriculture.Domain.Interface.SheepFileModelInterface;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace IntelligentAgriculture.Services
{
    public class PregnancyService:IPregnancyService
    {
        private readonly IPregnancyRepository _pregnancyRepository;
        private readonly IEarTagReposiotry _earTagReposiotry;
        private readonly IBreedingInfoRepository  _breedingInfoRepository;
        //历史
        private readonly IHistoryRecordRepository _historyRecordRepository;
        private readonly IridegRepository _iridegRepository;
        private readonly IColumnManRepository _columnManRepository;
        //档案
        private readonly ISheepFileModelRepository _sheepFileModelRepository;
        //转舍
        private readonly ISheepRescissionRepository _sheepRescissionRepository;
        private readonly AgricultureDbContext _context;
        private readonly IMapper _mapper;
        public PregnancyService(IPregnancyRepository pregnancyRepository, IEarTagReposiotry earTagReposiotry, IBreedingInfoRepository breedingInfoRepository, IridegRepository iridegRepository, IColumnManRepository columnManRepository, IHistoryRecordRepository historyRecordRepository, ISheepFileModelRepository sheepFileModelRepository, ISheepRescissionRepository sheepRescissionRepository, AgricultureDbContext context, IMapper mapper)
        {
            _pregnancyRepository = pregnancyRepository;
            _earTagReposiotry = earTagReposiotry;
            _breedingInfoRepository = breedingInfoRepository;
            _iridegRepository = iridegRepository;
            _columnManRepository= columnManRepository;
            _historyRecordRepository = historyRecordRepository;
            _sheepFileModelRepository = sheepFileModelRepository;
            _sheepRescissionRepository = sheepRescissionRepository;
            _context = context;
            _mapper = mapper;
        }
        /// <summary>
        /// 种母妊检列表
        /// </summary>
        /// <param name="startPregnancyDate"></param>
        /// <param name="endPregnancyDate"></param>
        /// <param name="eartag"></param>
        /// <param name="userId"></param>
        /// <param name="pregnancyResult"></param>
        /// <param name="parityNum"></param>
        /// <returns></returns>
        public async Task<PageOutput<PregnancyOutput>> GetPageOutputAsync(string? startPregnancyDate, string? endPregnancyDate, string? eartag, int userId, int? pregnancyResult, int? parityNum,int pageIndex,int pageSize)
        {
            var query = await _pregnancyRepository.GetSheeppregnancy();
            var rigin = _iridegRepository.Showinfo();
            var columns = _columnManRepository.GetShow();
            var entity = from pregnancy in query
                         join eartags in _context.Eartags on pregnancy.EarTag equals eartags.EarTagNumber
                         join ridgepole in rigin on pregnancy.CurrentBuilding equals ridgepole.RidgepoleId
                         join column in columns on pregnancy.CurrentField equals column.ColumnManagementId
                         select new PregnancyOutput
                         {
                             EarTag = eartags.EarTagNumber,
                             PregnancyDate = pregnancy.PregnancyDate,
                             PregnancyResult = pregnancy.PregnancyResult,
                             PregnancyManner = pregnancy.PregnancyManner,
                             ParityNum = pregnancy.ParityNum,
                             PregnancyNum = pregnancy.PregnancyNum,
                             //当前栋舍
                             CurrentBuilding = ridgepole.RidgepoleId,
                             BuildingName = rigin.FirstOrDefault(c => c.RidgepoleId == pregnancy.CurrentBuilding).RidgepoleName,
                             //当前栏位
                             CurrentField =column.ColumnManagementId,
                             ColumnName =columns.FirstOrDefault(c=>c.ColumnManagementId == pregnancy.CurrentField).ColumnName,
                             //转入栋舍
                             ToBuildingManageId = ridgepole.RidgepoleId,
                             ToBuildingName = rigin.FirstOrDefault(c => c.RidgepoleId == pregnancy.ToBuildingManageId).RidgepoleName,
                             //转入栏位
                             ToColumMangementId = column.ColumnManagementId,
                             ToColumnName = columns.FirstOrDefault(c => c.ColumnManagementId == pregnancy.ToColumMangementId).ColumnName,
                             DocumentNumber =pregnancy.DocumentNumber,
                             PregnancyContext =pregnancy.PregnancyContext,
                             PregnancyId =pregnancy.PregnancyId,
                             AuditDate =pregnancy.AuditDate,
                             AuditName =pregnancy.AuditName,
                             CreateName =pregnancy.CreateName,
                             CreateTime =pregnancy.CreateTime,
                             UpdateName =pregnancy.UpdateName,
                             UpdateTime =pregnancy.UpdateTime,
                             UserId =pregnancy.UserId,
                             IsDel =pregnancy.IsDel,
                         };
            if(!string.IsNullOrEmpty(startPregnancyDate))
            {
                entity = entity.Where(c => c.PregnancyDate >=  DateTime.Parse( startPregnancyDate));
            }
            if(!string.IsNullOrEmpty (endPregnancyDate))
            {
                entity = entity.Where(c => c.PregnancyDate <= DateTime.Parse(endPregnancyDate));
            }
            if(!string.IsNullOrEmpty(eartag))
            {
                entity =entity.Where(c=>c.EarTag == eartag);
            }
            if(userId>0)
            {
                entity =entity.Where(c=>c.UserId == userId);
            }
            if(pregnancyResult>0)
            {
                entity = entity.Where(c => c.PregnancyResult == pregnancyResult);
            }
            if(parityNum>0)
            {
                entity =entity.Where(c=>c.PregnancyNum == parityNum);
            }
            var result = new PageOutput<PregnancyOutput>
            {
                TotalCount = entity.Count(),
                PageSize = pageSize,
            };
            entity = entity.OrderByDescending(c => c.CreateTime).Skip(pageSize * (pageIndex - 1)).Take(pageSize);
            result.Data =_mapper.Map<List<PregnancyOutput>>(entity);
            return result;
        }
        /// <summary>
        /// 种母妊检添加
        /// </summary>
        /// <param name="sheeppregnancy"></param>
        /// <returns></returns>
        public async Task<int> AddPregnancy(List<Sheeppregnancy> sheeppregnancy)
        {
            try
            {
                sheeppregnancy.ForEach(c =>
                {
                    c.CreateTime = DateTime.Now;
                    c.CreateName = "赵思彤";
                    c.UpdateTime = DateTime.Now;
                    c.IsDel = false;
                    c.DocumentNumber = YitIdHelper.NextId().ToString();
                });
                var entity = await _pregnancyRepository.AddPregnancy(sheeppregnancy);

                //获取耳号
                var des =sheeppregnancy.Select(c=>c.EarTag).ToList();
                //获取配种信息
                var BList = await _breedingInfoRepository.GetBreedinginfoAsync();
                //添加妊检 删除配种信息
                var breed = BList.Where(c => des.Contains(c.EarTag)).ToList();
                breed.ForEach(c =>
                {
                    c.EarTag = sheeppregnancy.FirstOrDefault(s => s.EarTag == c.EarTag).EarTag;
                    c.Isdel = true;
                });
                 await _breedingInfoRepository.UpdBreedinginfos(breed);
                if (breed == null)
                {
                    return 0;//添加失败
                }
                //获取种母历史记录
                var HList =await _historyRecordRepository.GetHistoryRecordsAsync();
                var history = HList.Where(c=>des.Contains(c.EarTag)).ToList();
                history.ForEach(c =>
                {
                    c.EarTag = sheeppregnancy.FirstOrDefault(s => s.EarTag == c.EarTag).EarTag;
                    c.PregnancyDate = sheeppregnancy.FirstOrDefault(s => s.EarTag == c.EarTag).PregnancyDate;
                    c.PregnancyResult = sheeppregnancy.FirstOrDefault(s => s.EarTag == c.EarTag).PregnancyResult;
                });
                await _historyRecordRepository.ListUpdateHisRecordAsync(history);
                //获取档案表
                var SList = await _sheepFileModelRepository.GetSheepfilemodels();
                var sheepfile = SList.Where(c => des.Contains(c.EarTag)).ToList();
                //修改档案表数据
                sheepfile.ForEach(c =>
                {
                    c.EarTag = sheeppregnancy.FirstOrDefault(s => s.EarTag == c.EarTag).EarTag;
                    c.BuildingId = sheeppregnancy.FirstOrDefault(s => s.EarTag == c.EarTag).ToBuildingManageId;
                    c.ColumnId = sheeppregnancy.FirstOrDefault(s => c.EarTag == c.EarTag).ToColumMangementId;
                    c.ReproductionState = 7;
                    c.IsPregnancy = 1;
                });
                await _sheepFileModelRepository.UpdateListSheepFileModel(sheepfile);
                //添加羊只转舍
                var sheepRescission = sheeppregnancy.Select(item => new Sheeprescission
                {
                    SheepRescissionDate = DateTime.Now,
                    EarTag = item.EarTag,
                    RoundType = 2,
                    OutBuildingManageId = item.CurrentBuilding,
                    OutColumMangementId = item.CurrentField,
                    ToBuildingManageId = item.ToBuildingManageId,
                    ToColumMangementId = item.ToColumMangementId,
                    SheepType = 2,
                    Variety = sheepfile.FirstOrDefault(c => c.EarTag == item.EarTag)?.Variety,
                    SheepRescissionSex = sheepfile.FirstOrDefault(c => c.EarTag == item.EarTag)?.SheepSex,
                    CreateName = item.CreateName,
                    CreateTime = DateTime.Now,
                    UpdateName = item.UpdateName,
                    UpdateTime = DateTime.Now,
                    DocumentNumber = YitIdHelper.NextId().ToString(),
                    Isdel = item.IsDel

                }).ToList();

                return await _sheepRescissionRepository.AddSheepRescission(sheepRescission);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 种母妊检删除
        /// </summary>
        /// <param name="pregnancyId"></param>
        /// <returns></returns>
        public async Task<int> DelePregnancy(string? eartag)
        {
            try
            {
                var result = await _pregnancyRepository.DelePregnancy(eartag);
                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }
        
        
    }
}
